package com.wxq.search.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wxq.common.to.SkuEsModel;
import com.wxq.search.config.ElasticSearchConfig;
import com.wxq.search.constant.EsConstant;
import com.wxq.search.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Jim
 * @date 3:14 下午 2022/4/1
 * @description 商品上架
 * @email:huwmz04153277@126.com
 */
@Slf4j
@Service("productService")
public class ProductServiceImpl implements ProductService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 上架商品
     *
     * @param skuEsModelList
     * @return
     */

    @Override
    public boolean productUp(List<SkuEsModel> skuEsModelList) throws IOException {
        //给es中建立索引，并建立好映射关系
        //批量保存
        BulkRequest bulkRequest = new BulkRequest();
        skuEsModelList.forEach(skuEsModel -> {
            //制定索引
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            //制定索引id
            indexRequest.id(skuEsModel.getSkuId().toString());
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonString = null;
            try {
                jsonString = objectMapper.writeValueAsString(skuEsModel);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            //设置数据
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        BulkResponse bulk = null;
        bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
        //处理批量保存错误
        boolean b = bulk.hasFailures();
        List<String> collect = Arrays.stream(bulk.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
        log.info("商品上架:{}", collect);
        return b;
    }
}
